﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using clf.weighing.entity;


namespace weighing
{
    public class RolePermissionDao : BaseDao<RolePermission>
    {
        #region instance

        private static RolePermissionDao? instance;
        public static RolePermissionDao Instance => instance ??= new RolePermissionDao();

        public override string GetTableName()
        {
            return TableName.sys_role_permission.ToString();
        }

        #endregion



        private readonly string tableName = TableName.sys_role_permission.ToString();

        public int Insert(RolePermission rolePermission)
        {
            string sql = SqlBuilder.GetInsertSql(rolePermission, tableName);
            return Sqlite.Insert(sql);
        }

        public  int Update(RolePermission rolePermission)
        {
            string sql = SqlBuilder.GetUpdateSql(rolePermission, tableName);
            return Sqlite.Update(sql);
        }

        public List<RolePermission> GetListByRoleId(long roleId)
        {
            string condition = $"{RolePermissionField.role_id} = {roleId}";
            string order = $"{RolePermissionField.permission_id} asc";
            string sql = SqlBuilder.GetSelectSql(tableName, null, condition, null, null, order);
            var data = Sqlite.Select<RolePermission>(sql);
            return data;
        }

        /// <summary>
        /// 删除之前的，增后来的
        /// </summary>
        /// <param name="roleId">角色Id</param>
        /// <param name="rolePermissions"></param>
        /// <returns></returns>
        public int Update(long roleId, List<RolePermission> rolePermissions)
        {
            // userid ==1 为超管 不可操作
            if (roleId <= 0 || roleId == 1) return 0;
            string delSql = SqlBuilder.GetDeleteSql(tableName, $"{RolePermissionField.role_id} = {roleId}");
            if (rolePermissions == null || rolePermissions.Count == 0)
            {
                return Sqlite.Delete(delSql);
            }
            string[] Sqls = new string[rolePermissions.Count + 1];

            Sqls[0] = delSql;

            for (int i = 1; i <= rolePermissions.Count; i++)
            {
                string inSql = SqlBuilder.GetInsertSql(rolePermissions[i - 1], tableName);
                Thread.Sleep(90);
                Sqls[i] = inSql;
            }
            int res = Sqlite.TransactionExecute(Sqls);
            return res;
        }
    }
}
